﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using MayhemCore;
using MayhemWpf.ModuleTypes;
using System.ComponentModel;
using MayhemWpf.UserControls;
using OL2012Mayhem.Wpf;
using OL2012Mayhem.Helpers;
using System.Windows.Threading;

namespace OL2012Mayhem.Events
{
    public static class MedalTypes
    {
        public static string AllMedals = "All";
        public static string GoldMedals = "Gold";
        public static string SilverMedals = "Silver";
        public static string BronzeMedals = "Bronze";
    }
    

    [DataContract]
    [MayhemModule("OL 2012 Medals", "Triggers when a country wins a medal")]
    public class OL2012Medals : EventBase, IWpfConfigurable
    {
        private DispatcherTimer dTimer;

        private int previousCount = 0;

        [DataMember]
        private string country;

        [DataMember]
        private string url;

        [DataMember]
        private string medalType;

        protected override void OnLoadDefaults()
        {
            country = "United States";
            medalType = MedalTypes.AllMedals;
        }

        protected override void OnAfterLoad()
        {
            dTimer = new DispatcherTimer();
            dTimer.Interval = new TimeSpan(0, 5, 0);
            dTimer.Tick += new EventHandler(dTimer_Tick);
        }

        protected override void OnEnabling(EnablingEventArgs e)
        {
            previousCount = CollectDataHelper.GetMedalCount(url, medalType);
            dTimer.Start();
        }

        void dTimer_Tick(object sender, EventArgs e)
        {
            var count = CollectDataHelper.GetMedalCount(url, medalType);
            if (count > 0)
            {
                bool trigger = count > previousCount;
                if (trigger)
                {
                    Trigger();
                    previousCount = count;
                }
            }
        }

        protected override void OnDisabled(DisabledEventArgs e)
        {
            dTimer.Stop();
        }

        public WpfConfiguration ConfigurationControl
        {
            get
            {
                return new OL2012MedalsConfig(country, medalType);
            }
        }

        public void OnSaved(WpfConfiguration configurationControl)
        {
            OL2012MedalsConfig config = configurationControl as OL2012MedalsConfig;
            country = config.Country;
            url = config.Url;
            medalType = config.MedalType;

        }

        public string GetConfigString()
        {
            return "Monitors " + medalType.ToLower() + " medals for " + country.ToString();
        }

    }
}
